package com.baizhi.lql.service;

import com.baizhi.lql.dao.AdminDao;
import com.baizhi.lql.entity.Admin;
import com.baizhi.lql.utils.ImageCodeUtil;
import com.baizhi.lql.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service("adminService")
@Transactional
public class AdminServiceImpl implements AdminService{
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private RedisTemplate redisTemplate;

    //生成验证码
    public Map<String,String> getImageCodes() throws IOException {
        Map<String,String> map = new HashMap<>();
        //调用工具类  获取随机验证码字符
        String code = ImageCodeUtil.getSecurityCode();
        //调用工具类  根据随机码  生成图片 base64 形式
        String imgBase64 = ImageCodeUtil.careateImgBase64(code);
        // 把base64 图片信息  存入map
        map.put("imgBase64",imgBase64);

        // 获取UUID
        String uuid = UUID.randomUUID().toString();
        // 把UUID 存入 map
        map.put("token",uuid);

        // 往redis 中存 验证码
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("CODE_"+uuid,code,1, TimeUnit.MINUTES);

        return map;
    }

    // 登录检查
    public Map<String,String> login(@RequestBody Admin admin,String token){
        Map<String,String> map = new HashMap<>();
        // 从redis中获取服务器上验证码
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object obj = valueOperations.get("CODE_" + token);

        // 检查验证码
        if(obj == null){  // 验证码过期
            map.put("message","验证码过期");
            map.put("state","error");
            return map;
        }
        String serverCode = obj.toString();
        if(!admin.getEncode().equals(serverCode)){  // 验证码错误
            map.put("message","验证码错误");
            map.put("state","error");
            return map;
        }
        // 验证码正确，检查账号密码
        Admin admin1 = adminDao.selectName(admin.getUsername());
        if(admin1 == null){
            map.put("state","error");
            return map;
        }else { // 账号存在
            if(admin1.getStatus() == "0"){
                map.put("message","账户已被冻结");
                map.put("state","error");
                return map;
            }
            // 获取输入的密码
            // 加DB相同的盐
            String md5Pwd = admin1.getSalt() + admin.getPassword() + admin1.getSalt();
            //对加盐后的密码 MD5  MD5Pwd
            String md5Code = Md5Utils.getMd5Code(md5Pwd);

            if(md5Code.equals(admin1.getPassword())){ // ok
                map.put("message",token);
                map.put("state","success");
               valueOperations.set("TOKEN_"+token,admin1);
            }else {
                map.put("message","密码错误");
                map.put("state","error");
                return map;
            }
        }
            return map;
    }
     // 获取登录用户信息
      public  Admin getUserInfo(String token){
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            ValueOperations valueOperations = redisTemplate.opsForValue();
            return (Admin)valueOperations.get("TOKEN_" + token);
      }
        // 安全退出
        public void logout(String token){
            // 从redis 中删除
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.delete("TOKEN_"+token);
      }

    @Override
    public void reg(Admin admin) {
        String password = admin.getPassword();
        //调用工具类  获取随机盐
        String salt = Md5Utils.getSalt(6);
        // 对原始密码  加随机盐
        String saltPwd = salt + password + salt;
        // 调用工具类 加对随机盐后的密码进行MD5加密
        String md5Code = Md5Utils.getMd5Code(saltPwd);
        // 对传递过来的管理员数据  进行数据加工
        admin.setPassword(md5Code);
        admin.setSalt(salt);

        adminDao.insert(admin);
    }
/*
    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Admin queryName(String username) {
        return adminDao.selectName(username);
    }*/
}
